﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameTimeSystemFacade : MonoBehaviour {

    private static GameTimeSystemFacade inst;

    public static GameTimeSystemFacade Inst
    {
        get
        {
            if (inst == null)
            {
                GameObject go = new GameObject("GameTimeSystemFacade");
                inst = go.AddComponent<GameTimeSystemFacade>();
                MonoBehaviour.DontDestroyOnLoad(go);
            }
            return inst;

        }
    } 

    private List<IGameTimer> Timers = new List<IGameTimer>();

    private List<IGameTimer> SpareTimers = new List<IGameTimer>();
    

    public IGameTimer RegisterTimer(float edgeTime,float timeScale, Action onTimeOut, Action OnPause = null)
    {
        if (SpareTimers.Count > 0)
        {
            SpareTimers[0].EdgeTime = edgeTime;
            SpareTimers[0].TimeScale = timeScale;
            SpareTimers[0].OnTimeOut += onTimeOut;
            SpareTimers[0].OnPause += OnPause;

            Timers.Add(SpareTimers[0]);
            SpareTimers.RemoveAt(0);
        }
        else
        {
            GameTimer timer = new GameTimer();
            timer.SetData(edgeTime, onTimeOut, timeScale);
            timer.OnPause += OnPause;

            Timers.Add(timer);
        }

        
        return Timers[Timers.Count - 1];
    }

    public void BreakTimer(IGameTimer timer)
    {
        timer.IsBreak = true;
    }

    private void Update()
    {
        Timers.Sort((item1, item2) => {
            if (item1.IsTimeOut && !item2.IsTimeOut)
            {
                return 1;
            }
            else if (!item1.IsTimeOut && item2.IsTimeOut)
            {
                return -1;
            }
            return 0;
        });

        for (int i = Timers.Count - 1; i >= 0; i--)
        {
            if (Timers[i].IsTimeOut)
            {
                SpareTimers.Add(Timers[i]);
                Timers.RemoveAt(i);
            }
        }

        for (int i = 0; i < Timers.Count; i++)
        {
            Timers[i].Polling(Time.deltaTime);
        }

    }

}
